import axios from 'axios'
import Router from '../router'
/* global __APIHOST__ */

// 设置请求基地址
console.log(__APIHOST__, '==__APIHOST__==')
axios.defaults.baseURL = __APIHOST__
// axios.defaults.baseURL = '/api' // 开启跨域代理
axios.defaults.headers.post['Content-Type'] = 'application/json'
axios.defaults.withCredentials = true
axios.defaults.transformRequest = function (request) {
  return JSON.stringify(request)
}
axios.interceptors.request.use(
  config => {
    return config
  },
  error => {
    return Promise.reject(error)
  }
)
axios.defaults.timeout = 36000000 // 设置超时时间
axios.interceptors.response.use(
  response => {
    // 检测某种状态进行重定向
    if (response.data.code === 403) {
      Router.push({
        name: 'login'
      })
    }
    return response
  },
  error => {
    return Promise.resolve(error.response)
  }
)
export function fetchPost (url, params) {
  return new Promise((resolve, reject) => {
    axios.post(url, params)
      .then(response => {
        resolve(response.data)
      }, err => {
        reject(err)
      })
      .catch((error) => {
        reject(error)
      })
  })
}
// 返回一个Promise(发送get请求)
export function fetchGet (url, param) {
  return new Promise((resolve, reject) => {
    axios.get(url, { params: param })
      .then(response => {
        resolve(response.data)
      }, err => {
        reject(err)
      })
      .catch((error) => {
        reject(error)
      })
  })
}
export default axios
